package org.dei.perla.sys.device.channel.frame.address.concrete;

import java.net.InetAddress;
import java.net.InetSocketAddress;

import org.dei.perla.sys.device.channel.frame.address.FrameAddress;


/**
 * Rappresenta un indirizzo socket <IP:Porta>
 */
public class SocketFrameAddress extends FrameAddress {
	
	/**
	 * Inizializza un indirizzo SocketFrameAddress
	 */
	public SocketFrameAddress() {
		super();
	}
	
	/**
	 * Inizializza un indirizzo SocketFrameAddress
	 * @param parAddress
	 */
	public SocketFrameAddress(InetSocketAddress parAddress) {
		super(parAddress);
	}
	
	/**
	 * Inizializza un indirizzo SocketFrameAddress
	 * @param parAddress
	 */
	public SocketFrameAddress(String parAddress) {
		this.setAddressFromString(parAddress);
	}
	
	@Override
	public boolean equals(FrameAddress parFrameAddress) {
		if ( parFrameAddress instanceof SocketFrameAddress ) {
			if ( this.getAddress().equals(((SocketFrameAddress)parFrameAddress).getAddress())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void setAddressFromString(String parAddress) {
		try {
			this.pAddress = new InetSocketAddress(
					
					InetAddress.getByName(parAddress.substring(0, parAddress.indexOf(":"))), 
					new Integer(parAddress.substring(parAddress.indexOf(":")+1, parAddress.length())));
		} catch (Exception e) {
			/**
			 * @todo eccezzione da gestire
			 */
			e.printStackTrace();
		}
	}
	
	public InetSocketAddress getAddress() {
		return (InetSocketAddress) this.pAddress;
	}

	@Override
	public String toString() {
		return "Indirizzo <IP:Porta>" + getAddress().getAddress().getHostAddress() + ":" + getAddress().getPort();
	}

}
